package flexlingo.utils
{
	import mx.utils.ArrayUtil;
	import mx.utils.StringUtil;
	
	public class LingoUtils 
	{
		public static function getIndexByID(source:Array,ID:String,value:*=null):int
		{
			
			var n:int = source.length;
	        for (var i:int = 0; i < n; i++)
	        {
	            if (source[i][ID] === value)
	                return i;
	        }
	
	        return -1;
		}
		
		public static function setByID(source:Array,item:Object,ID:String,value:*=null):Array
		{
			var index : int = getIndexByID(source,ID,value);
				
				if ( index == -1)
				{
					source.push(item);
				}
				else
				{
					source[index] = item;	
				}
			
			return source;
		}
		
		public static function getItemByIndex( item:Object,source:Array):int
		{
			return ArrayUtil.getItemIndex( item,source);
		}
		
		
		public static function replaceAll(input:String, replace:String, replaceWith:String):String
		{
			//change to StringBuilder
			var sb:String = new String();
			var found:Boolean = false;

			var sLen:Number = input.length;
			var rLen:Number = replace.length;

			for (var i:Number = 0; i < sLen; i++)
			{
				if(input.charAt(i) == replace.charAt(0))
				{   
					found = true;
					for(var j:Number = 0; j < rLen; j++)
					{
						if(!(input.charAt(i + j) == replace.charAt(j)))
						{
							found = false;
							break;
						}
					}

					if(found)
					{
						sb += replaceWith;
						i = i + (rLen - 1);
						continue;
					}
				}
				sb += input.charAt(i);
			}
			//TODO : if the string is not found, should we return the original
			//string?
			return sb;
		}
		
		
		public static function stringsAreEqual(s1:String, s2:String, caseSensitive:Boolean):Boolean
		{
			if(caseSensitive)
			{
				return (s1 == s2);
			}
			else
			{
				return (s1.toUpperCase() == s2.toUpperCase());
			}
		}
		
	
		public static function trim(input:String):String
		{
			return LingoUtils.ltrim(LingoUtils.rtrim(input));
		}


		public static function ltrim(input:String):String
		{
			var size:Number = input.length;
			for(var i:Number = 0; i < size; i++)
			{
				if(input.charCodeAt(i) > 32)
				{
					return input.substring(i);
				}
			}
			return "";
		}

		public static function rtrim(input:String):String
		{
			var size:Number = input.length;
			for(var i:Number = size; i > 0; i--)
			{
				if(input.charCodeAt(i - 1) > 32)
				{
					return input.substring(0, i);
				}
			}

			return "";
		}


		public static function beginsWith(input:String, prefix:String):Boolean
		{			
			return (prefix == input.substring(0, prefix.length));
		}	


		public static function endsWith(input:String, suffix:String):Boolean
		{
			return (suffix == input.substring(input.length - suffix.length));
		}	
		
		
	}
}

